package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @return
     */
    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        //获取到请求添加到数据库中
        categoryService.save(category);
        return R.success("新增成功");
    }

    @GetMapping("/page")
    //page=1&pageSize=10
    public R<Page<Category>> page(
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize
    ){
        //封装分页对象
        Page<Category> categoryPage = new Page<>(page,pageSize);

        //按sort来排序
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        //调用方法查询
        Page<Category> pageInfo = categoryService.page(categoryPage,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改菜品分类
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        //调用方法修改
        if (categoryService.updateById(category)) {
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 删除菜品分类
     * @return
     */
    @DeleteMapping
    public R<String> deleCategory(@RequestParam("id") Long id){
        //调用方法修改
        /*if (categoryService.removeById(id)) {
            return R.success("删除成功");
        }*/
        categoryService.remove(id);
        return R.success("分类信息删除成功");
    }
    //http://localhost:8080/category/list?type=1

    /**
     * 查询菜品分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> categoryByType(Category category){
        //查询type为1时
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());

        //按sort降序来排序
        queryWrapper.orderByDesc(Category::getSort);

        //查询
        List<Category> categoryList = categoryService.list(queryWrapper);
        return R.success(categoryList);
    }
}
